<script setup lang="ts">
import myTopic from "@/composables/myTopic.ts";
import myAuth from "@/composables/myAuth.ts";
import myLocalStore from "@/composables/myLocalStore.ts";
import dayjs from "dayjs";
import myUser from "@/composables/myUser.ts";
const {is_favorite,getIsFavorite,toggleFavorite} = myUser();
const {isLogin,isSuperAdmin} = myAuth();
const userInfo = myLocalStore().get('userInfo');
const u_id = userInfo?.id;
const route = useRoute();
const t_id = route.params?.t_id
const {topicDetail,getTopicDetail,delTopic} = myTopic()
await getTopicDetail(t_id);
await getIsFavorite(u_id,t_id);
const toggle_favorite= async ()=>{
  is_favorite.value = !is_favorite.value;
  await toggleFavorite(t_id)
}


</script>

<template>
<main class="all" v-if="topicDetail">
  <h4>{{topicDetail.title}}</h4>
  <section class="author">
    <div class="name">
      <icon-me />
      <span>{{topicDetail.user.name}}</span>
    </div>
    <div class="time">
      <icon-stopwatch-start />
      <span>{{dayjs(topicDetail.created_at).fromNow()}}</span>
    </div>
    <div class="cat">
      <icon-all-application />
      <router-link class="hover:text-green-600"
                   :to="{name:'per.cat',params:{c_id:topicDetail.cat.id}}">{{topicDetail.cat.title}}
      </router-link>
    </div>
    <div class="favorite" v-if="u_id">
      <icon-star size="16"
                 @click="toggle_favorite"
                 :class="{'text-amber-600':is_favorite}"/>
    </div>
  </section>
  <section class="buttons">
    <el-button-group size="small">
      <el-button type="success" v-if="isLogin()" @click="$router.push({name:'front.topic.add'})">
        <icon-add />&nbsp;新增
      </el-button>
      <el-button type="primary" @click="$router.push({name:'front.topic.edit',params:{t_id}})" v-if="isSuperAdmin() || (topicDetail.user.id == userInfo?.id)">
        <icon-editor />&nbsp;编辑
      </el-button>
      <el-button type="danger"
                 @click="delTopic(topicDetail.id)"
                 v-if="isSuperAdmin() || (topicDetail.user.id == userInfo?.id)"><icon-delete />
        &nbsp;删除</el-button>

      <el-button type="warning" @click="$router.push({name:'home'})"><icon-back />&nbsp;返回</el-button>
    </el-button-group>
  </section>
  <section class="content">
    <markdown-markdown-preview :text="topicDetail.html"/>
  </section>
  <my-comment-list :t_id="topicDetail.id"/>
</main>
</template>

<style lang="scss" scoped>
main.all{
  @apply flex flex-col justify-start items-center min-h-screen;
  h4{
    @apply font-bold text-slate-700 p-3 text-[18px];
  }
  section.author{
    @apply flex gap-2 items-center justify-center;
    div.name,div.time,div.cat,div.favorite{
      @apply flex items-center gap-1 text-xs text-slate-500 p-3 cursor-pointer;
    }
  }
  section.buttons{
    @apply pb-3;
  }
  section.content{
    @apply border border-slate-300 rounded p-3 w-full;
  }

}
</style>